<template>
    <div class="el-divider" ref="dividerRef">
        <div class="el-divider__left" />
        <span class="el-divider__text" ref="textRef">
            <slot />
        </span>
        <div class="el-divider__right" />
    </div>
</template>

<script setup>
import { getElementSize } from "@/utils/tools"

const props = defineProps({
    contentPosition: {
        type: String,
        default: "left",
        validator(val) {
            return ["left", "right", "center"].includes(val)
        }
    },
    height: {
        type: [Number, String],
        default: 0
    }
})

const textRef = ref(null)
const dividerRef = ref(null)
const leftSize = ref(0)
const rightSize = ref(0)
watchEffect(() => {
    const textSize = getElementSize(textRef).width || 0
    const short = "40px"
    const half = "calc((100% - " + textSize + "px) / 2)"
    const length = "calc(100% - 40px - " + textSize + "px)"
    leftSize.value = props.contentPosition === "left" ? short : props.contentPosition === "right" ? length : half
    rightSize.value = props.contentPosition === "right" ? short : props.contentPosition === "left" ? length : half
})

const height = computed(() => {
    //判断props.height是数字时，添加px，否则直接返回props.height
    return props.height ? /^\d+(\.\d+)?$/.test(props.height) ? props.height + "px" : props.height : "50px"
})
</script>

<style>
.el-divider {
    display: flex;
    align-items: center;
    position: relative;
    margin: 0;
    padding: 0;
    color: #606266;
    font-size: 14px;
    white-space: nowrap;
    border-color: #dcdfe6;
    height: v-bind(height);
    width: 100%;
}

.el-divider__text {
    position: relative;
    background: transparent;
    font-size: var(--font-size);
    font-weight: var(--font-weight);
}

.el-divider__text:empty {
    padding: 0;
}

.el-divider__left {
    box-shadow: 0px 1px 0px 0px var(--el-input-border-color, var(--el-border-color)) inset;
    width: v-bind(leftSize);
    height: 1px;
}

.el-divider__right {
    box-shadow: 0px 1px 0px 0px var(--el-input-border-color, var(--el-border-color)) inset;
    width: v-bind(rightSize);
    height: 1px;
}
</style>